package cqrtplm.aop;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hustcad.plm.pdm.iba.model.dto.SaveIBAInputDTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.exception.MessageException;
import com.ty.basic.vo.IbaAttrsVO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.mapper.StoragePlanningMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author fxw
 * @version 1.0
 * @ClassName CheckInTheLogicalAOP
 * @Description 检入逻辑切面
 * @since 2025/11/5 20:45
 */
@Aspect
@Component
@Slf4j
public class DocCheckInTheLogicalAOP {


    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;

    @Resource
    private StoragePlanningMapper storagePlanningMapper;


    @Pointcut("execution(* com.hustcad.plm.pdm.iteration.service.impl.TyplmIterationServiceImpl.checkIn(..))")
    public void checkInTheLogicalPointcut() {}


    /**
     * 更具图号和编码去重
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("checkInTheLogicalPointcut()")
    @Transactional(rollbackFor = MessageException.class)
    public Object checkInTheLogical(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] arg = joinPoint.getArgs();
        String oid = (String) arg[0];
        String typeOtype = (String) arg[1];


        if (!typeOtype.contains(TableTypeConstrant.TY_CADDOC_OTYPE )) {
            return joinPoint.proceed();
        }

        List<IbaAttrsVO> cadDocDO = typeJudgment(oid,typeOtype);

        if (ObjectUtils.isEmpty(cadDocDO)) {
            return joinPoint.proceed();
        }

        Map<String, String> ibaAttributeMap = cadDocDO.parallelStream().collect(
                Collectors.toMap(IbaAttrsVO::getKey, IbaAttrsVO::getValue));

        String exclusiveSupplierCode = ibaAttributeMap.get("ExclusiveSupplierCode");

        if (ObjectUtils.isNull(exclusiveSupplierCode)) {
            String dedicatedSuppliers = ibaAttributeMap.get("DedicatedSuppliers");
            if (ObjectUtils.isNull(dedicatedSuppliers)) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                        "图纸的专属供应商不存在");
            }

            String[] splitSuppliers = dedicatedSuppliers.split("[|\\s]");

            if (splitSuppliers.length < 2) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                        "图纸的专属供应商不存在");
            }

            String updatedBusinessEdition = splitSuppliers[1];
            if (ObjectUtils.isEmpty(updatedBusinessEdition)) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                        "图纸的专属供应商不存在");
            }

            IbaDTO ibaDTO = new IbaDTO();
            ibaDTO.setKey("ExclusiveSupplierCode");
            ibaDTO.setValue(updatedBusinessEdition);

            SaveIBAInputDTO saveIBAInputDTO = new SaveIBAInputDTO();
            saveIBAInputDTO.setPartAtts(Collections.singletonList(ibaDTO));
            typlmAttributeValueService.batchSaveIBAAttributeValues(saveIBAInputDTO, new CTyEntityBaseDO(
                    Convert.toBigInteger(oid), TableTypeConstrant.TY_TYPE_OTYPE), false);

            String exclusiveSupplier = storagePlanningMapper.queryExtendedAttributes(oid, "专属供应商编码");
            String patternCode = storagePlanningMapper.queryExtendedAttributes(oid, "图样代号");

            if (ObjectUtils.isEmpty(exclusiveSupplier) || ObjectUtils.isEmpty(patternCode)) {

                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                       "图纸的专属供应商或图样代号为空");
            }

            if (storagePlanningMapper.theExclusiveSupplierCodeOfThePictureNumberIsWeighed(
                    exclusiveSupplier + "|" + patternCode,"|") > 0 ||
                    storagePlanningMapper.theExclusiveSupplierCodeOfThePictureNumberIsWeighed(
                            exclusiveSupplier + " " + patternCode," ") > 0) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                        "图纸的图样代号已存在");
            }
        }
        return joinPoint.proceed();
    }

    private List<IbaAttrsVO> typeJudgment(String oid,String typeOtype){
           if(typeOtype.contains(TableTypeConstrant.TY_CADDOC_OTYPE)){
               return  this.typlmAttributeValueService.getobjAllAttrValue(Convert.toBigInteger(oid),
                                                                          TableTypeConstrant.TY_CADDOC_OTYPE);

           }else{
               return this.typlmAttributeValueService.getobjAllAttrValue(Convert.toBigInteger(oid),
                                                                        TableTypeConstrant.TY_DOC_OTYPE);
           }

    }


}